<template>
  <div class="account-manage-index sub-margin">
    <!-- <div class="sub-page-title">用户管理</div> -->
    <div class="content">
      <div class="left-con">
        <OrganList :source="oragnList" @node-click="onOrganClick"></OrganList>
      </div>
      <div class="right-con">
        <AccountTable
          ref="accountTable"
          :source="userList"
          :post-code="searchForm.postCode"
          @edit-account="openDialog"
          @update-account="updateAccount"
          @del-account="delAccount"
          @drop-account="dropAccount">
          <div slot="search" class="search-box">
            <div class="search-left">
              <div class="search-item">
                <el-radio-group size="small" v-model="searchForm.postCode" class="radio-btn" @input="onRoleChange">
                  <el-radio-button label="current">当前用户</el-radio-button>
                  <el-radio-button label="history">历史用户</el-radio-button>
                </el-radio-group>
              </div>
              <div class="search-item">
                <el-input
                  placeholder="请输入内容"
                  v-model.trim="searchForm.key"
                  size="small"
                  clearable
                  @keyup.enter.native="onTableSearch">
                  <el-button slot="append" icon="el-icon-search" @click.stop="onTableSearch"></el-button>
                </el-input>
              </div>
            </div>
            <div class="search-right">
              <el-button
                v-if="searchForm.postCode === 'current'"
                type="primary"
                size="small"
                icon="el-icon-plus"
                @click.stop="onAddEdit">
                添加用户
              </el-button>
            </div>
          </div>
          <pagination
            slot="pagination"
            :page-size="pageParam.pageSize"
            :total="pageParam.totalSize"
            :current-page="pageParam.currentPage"
            @change="onPageChange"></pagination>
        </AccountTable>
      </div>
    </div>
    <AccountDialog
      :visible.sync="showDialog"
      :info="curAccount"
      @submit="onAccountSubmit"
      @renewData="onTableSearch"></AccountDialog>
  </div>
</template>
<script>
import pagination from '@com/pagination'
import AccountTable from './components/AccountTable'
import AccountDialog from './components/AccountDialog'
import OrganList from './components/OrganList.vue'
import {
  listUserData,
  saveOrEditUser,
  getUiasUserDetail,
  deleteUserInfo,
  delOrgan,
  updateUserStatus,
  listRecursiveOrgan,
  listFailureUserData,
  updateOrderByUser,
} from '@api/modules/system.js'
import { logout } from '@api/modules/user.js'
import { USER_STATUS } from '@utility/dict.js'

export default {
  name: 'accountManageIndex',
  components: { pagination, AccountTable, AccountDialog, OrganList },
  data() {
    return {
      searchForm: {
        key: '',
        postCode: 'current',
        status: '',
        orgId: '',
      },
      statusList: USER_STATUS._label,
      userList: [],
      showDialog: false,
      curAccount: {},
      pageParam: {
        currentPage: 1,
        pageSize: 10,
        totalSize: 0,
      },
      oragnList: [],
    }
  },
  created() {
    this.getOrganList()
  },
  methods: {
    async getOrganList() {
      const { status, data } = await listRecursiveOrgan()
      if (status === 200 && data && data.length) {
        this.oragnList = data
      } else {
        this.oragnList = []
      }
    },
    async initData() {
      const params = {
        pageNum: this.pageParam.currentPage,
        pageSize: this.pageParam.pageSize,
        ...this.searchForm,
      }
      let apiData = { status: 0, data: {} }
      if (this.searchForm.postCode === 'current') {
        apiData = await listUserData(params)
      } else {
        apiData = await listFailureUserData(params)
      }
      const status = apiData.status
      const data = apiData.data
      if (status === 200 && data) {
        const userList = data.content || []
        this.pageParam.totalSize = data.totalSize || 0
        userList.forEach((item, inx) => {
          item.orderNum = this.pageParam.pageSize * (this.pageParam.currentPage - 1) + (inx + 1)
        })
        this.userList = userList
      } else {
        this.pageParam.totalSize = 0
        this.userList = []
      }
    },
    onRoleChange() {
      this.searchForm.status = ''
      this.searchForm.key = ''
      this.pageParam.currentPage = 1
      this.pageParam.pageSize = 10
      this.initData()
    },
    onAddEdit() {
      this.openDialog()
    },
    onPageChange(obj) {
      this.pageParam.currentPage = obj.pageNumber
      this.pageParam.pageSize = obj.pageSize
      this.initData()
    },
    async updateAccount(obj, curId) {
      const { code, message } = await updateUserStatus(obj)
      if (code === 0) {
        this.$message.success(message || '更新成功')
        if (obj.id === curId) {
          this.ExitLogout()
        } else {
          this.initData()
        }
      }
    },
    async openDialog(obj) {
      if (obj && obj.id) {
        const detailInfo = await this.getUserDetail(obj.id)
        this.curAccount = {
          ...detailInfo,
          ...obj,
        }
      } else {
        this.curAccount = {}
      }
      this.showDialog = true
    },
    async getUserDetail(id) {
      const { status, data } = await getUiasUserDetail(id)
      if (status === 200 && data && data.id) {
        return data
      } else {
        return {}
      }
    },
    async delAccount(obj, curId) {
      // this.delOrg(obj)
      const { status } = await deleteUserInfo(obj.id)
      if (status === 200) {
        this.$message.success('删除成功')
        if (obj.id === curId) {
          this.ExitLogout()
        } else {
          if (this.userList.length === 1) {
            this.pageParam.currentPage = 1
            this.pageParam.pageSize = 10
          }
          this.initData()
        }
      }
    },
    ExitLogout() {
      logout()
        .then(res => {
          if (res.status === 200) {
            this.onLogout()
          }
        })
        .catch(() => {
          this.onLogout()
        })
    },
    onLogout() {
      localStorage.removeItem('token')
      localStorage.clear()
      sessionStorage.clear()
      this.$router.replace('/login')
    },
    async delOrg(obj) {
      if (!obj.orgId) {
        return false
      }
      const { status } = await delOrgan(obj.orgId)
      if (status === 200) {
        // to do something
      }
    },
    async onAccountSubmit(obj) {
      const { status, message = '' } = await saveOrEditUser({
        ...obj,
        loginPassword: obj.loginPassword,
        postDuty: obj.postDuty,
      })
      if (status === 200) {
        this.$message.success(message || '更新成功')
        this.initData()
      }
    },
    onOrganClick(data) {
      this.searchForm.orgId = data.id
      this.initData()
    },
    onTableSearch() {
      this.pageParam.currentPage = 1
      this.pageParam.pageSize = 10
      this.initData()
    },
    async dropAccount(data) {
      if (data) {
        const { status, message } = await updateOrderByUser(data)
        if (status === 200) {
          this.$message.success(message || '拖拽成功')
          this.initData()
        }
      } else {
        this.initData()
      }
    },
  },
}
</script>
<style lang="scss" scoped>
@import '@styles/layout.scss';
.account-manage-index {
  display: flex;
  flex-direction: column;
  height: 100%;
  align-items: stretch;
  .content {
    flex: 1;
    display: flex;
    align-items: stretch;
    padding: 20px 0;
    height: calc(100vh - 110px);
    .left-con {
      width: 280px;
      min-width: 280px;
      height: 100%;
      overflow: auto;
      position: relative;
      border-right: 1px solid #e4eaf0;
    }
    .right-con {
      // flex: 1;
      // width: 100%;
      // max-width: 1020px;
      width: calc(100% - 300px);
      margin: 0 auto;
      margin-left: 20px;
      position: relative;
      display: flex;
      flex-direction: column;
    }
  }
}
</style>
